<template>
  <div class="body">
  <!-- <div class="affix">
    <el-affix :offset="30">
      <el-button type="warning" @click="getEndNodeClick">获取章节</el-button>
      <div class="knowledgepointList" v-show="state.showKnowledgepointList">
        <el-button
          v-for="item in state.knowledgepointList"
          :key="item.name"
          :type="getButtonType(item.id)"
          text
          size="small"
          @click="linkKnowledgeClick(item.id,item.name)"
          >{{ item.name }}
        </el-button>
        <el-button
          text
          size="small"
          :type="getButtonType(2)"
          @click="hideKnowledgepointList"
        >关闭知识点</el-button>
        <el-button
          text
          size="small"
          :type="getButtonType(3)"
          @click="linkAllKnowledgeClick"
        >全关联</el-button>
      </div>
    </el-affix>
</div>  -->
 
  <h1>校对试题</h1>
  <div>
      <el-button type="primary" size="large" text @click="onClickReturnHome">《返回</el-button>
      <el-card class="box-card" v-for="(item, index) in state.returnQuestionList" :key="index"
        shadow="hover"
        :class="{active:state.selectIndex==index}"
        @click="selectCardClick(index)"
      >
          <template #header>
            <div class="card-header">
              <el-button type="danger" :icon="Delete" circle @click="onClickClearKnowledge(index)" />
              <span>题号：{{ item.order }} </span>
              <span>章节：
                <div v-for="(item_node, index) in item.node" :key="index">
                  {{ item_node.name }};
                </div>                
              </span>         
              
              <el-button :icon="EditPen" size="small" @click="editeOneQuestionClick(item,index)" ></el-button>
              <el-button :icon="Plus" size="small" @click="addOneQuestionClick(item,item.order)" ></el-button>
              <el-button :icon="Delete" size="small" @click="deleteOneQuestionClick(index)" ></el-button> 
              <el-button :icon="View" size="small" @mouseenter="viewOneQuestionClick(item,index)" ></el-button>       
            </div>
        </template>
        <div class="card-body">
            <p>【题型】{{item.type_cn}}</p>
            <div v-html="item.content" class="line-break"></div>
            <!-- <el-image v-for="url in item.images" :key="url" :src="url" style="width: 150px;height: 100px;" />   -->
            <p>【答案】</p>
            <div v-html="item.answer" class="line-break"></div>
             <p>【解析】</p>
            <div v-html="item.explain" class="line-break"></div>
            <!-- <el-image v-for="url in item.images_explain" :key="url" :src="url" style="width: 150px;height: 100px;" />   -->
    
        </div>
      </el-card>
  </div> 
  <ViewQuestionDetail ref="viewQuestionDetail" :question="state.question"></ViewQuestionDetail>
  <EditeOneQuestionDialogePrivate ref="editeOneQuestionDialogePrivate" :type="state.type" :question="state.question" :father_method="updateQuestionList" />
  <AddQuestionDialoge ref="addQuestionDialoge" :type="state.type" :knowledgepointId=state.nodeId :recoverQuestionList="recoverQuestionList" />
  <div>   
    <el-button 
      type="success" 
      @click="commitClick()" 
      :disabled="state.buttonDisabeled"
      v-loading="state.loading"
      element-loading-text="试卷正在提交，请耐心等待5s..."
      >提交到数据库
    </el-button>
  </div>

</div>
</template>
  
<script setup>
  import { reactive, ref, toRaw, onMounted, onUnmounted, } from 'vue'
  import { EditPen,Document, Download,View, ArrowDown, Plus,Delete, Picture } from '@element-plus/icons-vue'
  import { localGet, uploadPaperFileServer, deepClone,convertQuestionFormat,deleteQuestionItem, questionCutServer} from '@/utils'

  import ViewQuestionDetail from '@/views/ViewQuestionDetail.vue'
  import AddQuestionDialoge from '@/views/AddQuestionDialoge.vue'
  import { useRouter, useRoute } from 'vue-router'
  import { useStore } from 'vuex'
  import axios from 'axios'
  import { ElMessage, resultProps, ElMessageBox } from 'element-plus'  
import EditeOneQuestionDialogePrivate from './EditeOneQuestionDialogePrivate.vue'

  const viewQuestionDetail = ref()
  const showKnowledgepointList = ref(false)
  const editeOneQuestionDialogePrivate = ref()
  const store=useStore()
  const router = useRouter()
  const buttonTypeList = ['primary', 'success', 'info', 'warning', 'danger']
  const getButtonType =(value)=>{    
    return buttonTypeList[value % buttonTypeList.length]
  }
  
  const state = reactive({
    showKnowledgepointList:false,
    selectedNode: {id:0, name:''},
    loading:false,
    apiName:"/QuestionPrivateModelViewSet/create_question/",
    paperId:0,
    selectQuestionId:0,
    subjectId: 0,
    knowledgepointList:null,
    showKnowledgepointList:false,
    selectIndex:-1,
    paperInforVisible:true,
    token:localGet('token') || "",
    uploadPaperFileServer,
    returnQuestionList: null,
    selectedQuestion: Object,
    buttonDisabeled: false,
    dialogVisible: false,
    index:Number,
    type:"edit",
    nodeId:-1,
    showDrawer: false,
    paperInformation:{
      title:"",
      publish_time:"",
      is_joint:'true',
      open_level:'public',
      grade:'3',
    },
    importType:'',
  })
    // 返回到私人题库首页
    const onClickReturnHome=()=>{
    router.push("/userCenter/addNode")
  }
  // 清空所选的某个题目的关联知识点
  const onClickClearKnowledge = (index) =>{
    console.log('未清理前知识点id:',state.returnQuestionList[index].node)
    console.log('未清理前知识点中文:',state.returnQuestionList[index].node_cn)
    state.returnQuestionList[index].node=[]
    state.returnQuestionList[index].node_cn=[]
    console.log('清理后知识点id:',state.returnQuestionList[index].node)
    console.log('清理后知识点中文:',state.returnQuestionList[index].node_cn)
  }
  // 隐藏知识点列表
  const hideKnowledgepointList = () => {
    showKnowledgepointList.value = false
  }
  // 更新题目
  const updateQuestionList=(list_index,question)=>{
    console.log('题目index',list_index,question)
    state.returnQuestionList[list_index]=deepClone(question)
    console.log('所有题目：',state.returnQuestionList)
  }
  // 初始化页面钩子
  onMounted(()=>{
    state.returnQuestionList = deepClone(store.getters.getSelectQuestionList)

    console.log('从缓存中获取试题列表：', state.returnQuestionList)
  })
 
  //检查所有题目的知识点是否都已经关联
  const verifyKnowledgepointLinkQuestion=(questionList)=>{
    let flag=true
    let index=-1
    for(let i=0;i<questionList.length;i++){
      if (questionList[i].node.id <=0){
        flag=false
        index=i
        break
      }
    }
    return [flag, index]
  }
// 把知识点关联到题目
const linkKnowledgeClick=(knowledgeId,knowledgeName)=>{
  // console.log('知识点选中：',knowledgeId)
  if(state.selectIndex>=0 && knowledgeId>=1){
    if(state.returnQuestionList[state.selectIndex].node.includes(knowledgeId)){
      ElMessage.success("不可重复选择该知识点")
      return 0
    }
    state.returnQuestionList[state.selectIndex].node.push(knowledgeId)
    state.returnQuestionList[state.selectIndex].node_cn.push(knowledgeName)
    // state.returnQuestionList[state.selectIndex].node_cn=knowledgeName
    ElMessage.success("关联知识点成功！")
    console.log('试题关联值守点后：',state.returnQuestionList)
    return true
  }else
  if(state.selectIndex<0){
    ElMessage.error("关联知识点失败，请先选择题目")
    return false;
  }else
  if(knowledgeId<1){
    ElMessage.error("关联知识点失败，请先选择正确的知识点")
    return false;
  }
  else{
    ElMessage.error("关联知识点失败")
    return false;
  }
}
// 批量关联所有题目的知识点
const linkAllKnowledgeClick=() => {
  let knowledgeIdTemp = 1
  let knowledgeNameTemp = ''
  if(state.selectIndex >= 0){
      knowledgeIdTemp = state.returnQuestionList[state.selectIndex].node[0]
      knowledgeNameTemp = state.returnQuestionList[state.selectIndex].node_cn[0]
  } else if(knowledgeIdTemp = state.returnQuestionList[0].node.length>0){
    knowledgeIdTemp = state.returnQuestionList[0].node[0]
    knowledgeNameTemp = state.returnQuestionList[0].node_cn[0]
  }else {
    ElMessage.error("请先关联第一题")
    return false;
  }
  let flag = false  
  for(let i=0; i<state.returnQuestionList.length; i++){    
    if (!state.returnQuestionList[i].node.includes(knowledgeIdTemp)){
      state.returnQuestionList[i].node.push(knowledgeIdTemp)
      state.returnQuestionList[i].node_cn.push(knowledgeNameTemp)
      flag = true
    }
  }
  if(flag == true){
    ElMessage.success("关联成功")
    return true
  }
  return false

}
  // 选中卡片点击事件
  const selectCardClick=(index)=>{
    // console.log("选中题目索引：",index)
    state.selectIndex = index
  }
  // 获取某个顶端节点下的所有末端的章节
  const getEndNodeClick=()=>{
    let params = {top_node_id: store.getters.getNodeId}
    console.log("获取所有末端的章节")
    axios.get('/NodeModelViewSet/get_all_end_node',{params}).then(res => {
      console.log("获取知识点结果：",res)
      if (res.code==200){
        ElMessage.success('恭喜，获取知识点成功')
        state.knowledgepointList = deepClone(res.data.results)
        state.showKnowledgepointList = true     
      }else
      if(res.code==1099){
        ElMessage.error('参数错误，获取失败')
      }
      else
      if(res.code==1098){
        ElMessage.error('没有权限')  
      }
      else{
        ElMessage.error('服务器错误')
      } 
    })
    .catch((error)=>{
      console.log("error:", error)
    })   
  }
  // 双$更新成单$
  const convertDoubleDollarToSingle = (content_str)=>{
    while(content_str.includes('$$')){
      content_str = content_str.replace('$$', '$');
    }
    while(content_str.includes('\\\\')){
      content_str = content_str.replace('\\\\', '\\');
    }
    return content_str    
  }
  //查看单个题目详情
  const viewOneQuestionClick = (item)=>{
    state.question = deepClone(item)
    item.content = convertDoubleDollarToSingle(item.content)
    item.answer = convertDoubleDollarToSingle(item.answer)
    item.explain = convertDoubleDollarToSingle(item.explain)
    viewQuestionDetail.value.open(item)
  }
  //编辑题目
  const editeOneQuestionClick = (question,index)=>{
    // store.commit("setQuestion", question)
    // store.commit("setIndex",index)
    // state.type="edit"
    // state.selectedQuestion = question
    editeOneQuestionDialogePrivate.value.open(index,question)
  }
  // 增加一个空白的题目
  const addOneQuestionClick=(question_item, index)=>{
    let question_new = deepClone(question_item)
    question_new.content_front="待修改"
    question_new.answer_front="待修改"
    question_new.explain_front="待修改"
    question_new.order = index + 1
    state.returnQuestionList.splice(index+1,0,question_new)
  }
  // 当前位置删除一个题目
  const deleteOneQuestionClick=(index)=>{
    state.returnQuestionList.splice(index,1)
  }
  //从store中恢复题目
  const recoverQuestionList =()=>{
    const questionListIndex = store.state.index
    state.returnQuestionList[questionListIndex]=store.state.question
  }
  

  // 初始化数据
  const initQuestion=()=>{
    state.returnQuestionList=[];
    state.paperId=0;
    state.importType='';
  }

  // 调整试题列表，去掉无关项
  const reformatQuestionList=(q_list)=>{    
    let deleteList=["answer_front", "content_front","explain_front","images","images_answer","images_explain","knowledgepoint_cn","type_cn","grade"]
    let uploadQuestionList=deepClone(q_list)
    for(let item of uploadQuestionList){
      item=convertQuestionFormat(item)
      item=deleteQuestionItem(item,deleteList)
    }
    return uploadQuestionList
  }
  // 提交到数据库
  const commitClick=()=>{ 
    // 先检测是否所有题目都关联知识点
    let [ flag,index ]=verifyKnowledgepointLinkQuestion(state.returnQuestionList)
    index++;
    let s='第'+index.toString()+'题未关联知识点！'
    if (flag==false){
      ElMessage.error(s)
      return false
    }
    // 只发送所需要的属性
    let uploadQuestionListTemp=deepClone(state.returnQuestionList)
   
    let uploadQuestionList = []
    for(let i=0;i<uploadQuestionListTemp.length;i++){
      uploadQuestionList.push({
        content:uploadQuestionListTemp[i].content,
        answer:uploadQuestionListTemp[i].answer,
        explain:uploadQuestionListTemp[i].explain,        
        node:uploadQuestionListTemp[i].node,
        reference:uploadQuestionListTemp[i].reference,
        type:uploadQuestionListTemp[i].type,
        order:uploadQuestionListTemp[i].order,
        difficulty_level:uploadQuestionListTemp[i].difficulty_level,     
      })
    }
    let params={
      questionList:uploadQuestionList,
      type:state.importType,
      id:state.paperId,
      paperInformation:state.paperInformation,
    }
    console.log("要提交到数据库的api:",state.apiName)
    console.log("参数:",params)
    axios.post(state.apiName, params).then((result) => {
      // state.loading=false;
      // state.buttonDisabeled=false;
      console.log("服务器返回提交结果：", result)
      if(result.code==200){
        ElMessage.success( '题目提交成功,去个人中心查看发布结果！')
        var r=confirm("上传成功。是否去个人中心？");
            if (r==true){
                router.push("/userCenter/addNode")
            }else{
              router.push(`/showQuestionPrivate`)
            }
      }else
      if(result.code==201){        
        ElMessage.error( '题目提交成功，申请上线失败，请联系管理员!')
        var r=confirm("上传成功。是否去个人中心？");
            if (r==true){
                router.push("/userCenter/addNode")
            }else{
              router.push(`/showQuestionPrivate`)
            }
      }else{
        ElMessage.error( '提交错误，请联系管理员!') 
      }
    })  
    .catch((error)=>{
      console.log("发送错误：", error)
    })  

  }
</script>
<style scoped>
.active {
  background-color:#ffffff!important;
  border: 1px solid #409EFF;
}
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 10px;
    margin: 0;
    padding: 0;
    height: 10px;
  }
  .box-card {
    height:auto;
    overflow-y: auto;
  }
  .line-break{
  white-space: pre-wrap;
  }
  .block{
    display:block;
    width:  150px;
    height: 100px;
  }
  .inlineImage{
    display: inline;
    width:  150px;
    height: 100px;
  }
.affix{
    display: flex;
    flex-flow: row nowrap;
    justify-content: space-between;
    align-items: right;
    text-align: right;
}
.knowledgepointList{
  padding: 0rpx;
  margin: 0rpx;
  width: 900px;
  display: flex;
  flex-flow: row wrap;
  justify-content:left;
  align-items:flex-start; 
  background-color: rgb(228, 236, 239);
}
.body{
  width: 900px;
  display: flex;
  flex-flow: column nowrap;
  justify-content: left;
  align-items: flex-start; 
}
.download{
  display: flex;
  flex-flow: column nowrap;
  justify-content: space-between;
  align-items: flex-start; 
}
.downloadHeader{
  display: flex;
  flex-flow: row nowrap;
}
</style>